package com.xtayfjpk.zookeeper.test.master_workers.callback.worker;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.data.Stat;

import com.xtayfjpk.zookeeper.test.master_workers.Worker;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseDataCallback;

/**
 * 执行任务
 * @author zj
 *
 */
public class WorkerTaskDataCallback extends BaseDataCallback {
	private static final Logger LOGGER = Logger.getLogger(WorkerTaskDataCallback.class);
	private Worker worker;
	
	public WorkerTaskDataCallback(Worker worker) {
		this.worker = worker;
	}
	
	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx, byte[] data, Stat stat) {
		worker.getNewTaskData(path);
	}
	
	@Override
	protected void okCaseAction(int rc, String path, final Object ctx, final byte[] data, Stat stat) {
		worker.getExecutor().execute(new Runnable() {
			@Override
			public void run() {
				LOGGER.info("Executing your task: " + new String(data) + ", Done.");
				worker.createDoneStatus("/status/" + (String) ctx);
				worker.deleteDoneTask("/assign/worker-" + worker.getServerId() + "/" + (String) ctx);
			}
		});
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		LOGGER.error("Failed to get task data: ", KeeperException.create(Code.get(rc), path));
	}
}
